package com.logic.meeting.app.main;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Spinner;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.logic.meeting.app.R;
import com.logic.meeting.app.R2;
import com.logic.meeting.app.entity.BindEntity;
import com.logic.meeting.app.entity.MeetingListEntity;
import com.logic.meeting.app.entity.ProjectListEntity;
import com.logic.meeting.app.event.HomeRefreshEvent;
import com.logic.meeting.app.fusion.FusionCode;
import com.logic.meeting.app.fusion.FusionPre;
import com.logic.meeting.app.main.adapter.IndexSpanAdapter;
import com.logic.meeting.app.service.HeartBeatService;
import com.logic.meeting.app.util.ClickUtil;
import com.logic.meeting.app.util.DialogUtil;
import com.logic.meeting.app.util.OpenUDID;
import com.logic.meeting.core.delegates.AtmosDelegate;
import com.logic.meeting.core.net.HttpHelper;
import com.logic.meeting.core.net.HttpUrl;
import com.logic.meeting.core.net.callback.IError;
import com.logic.meeting.core.net.callback.IFailure;
import com.logic.meeting.core.net.callback.ISuccess;
import com.logic.meeting.core.util.StringUtil;
import com.logic.meeting.core.util.aes.AESUtil;
import com.logic.meeting.core.util.dimen.DimenUtil;
import com.logic.meeting.core.util.loader.AtmosLoader;
import com.logic.meeting.core.util.storage.AtmosPreference;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class IndexMachineSetDelegate extends AtmosDelegate {

    private List<String> projectList = new ArrayList<>();
    private List<String> meetingList = new ArrayList<>();
    private List<ProjectListEntity.DataBean.ListBean> mProjects;
    private List<MeetingListEntity.DataBean.ListBean> mMeetings;
    private String mSelectProjectId;
    private String mSelectMeetingId;
    private String mSelectMeetingName;

    @BindView(R2.id.tv_mac)
    AppCompatTextView tvMac;

    @BindView(R2.id.span_project)
    Spinner spanProject;
    @BindView(R2.id.span_meeting)
    Spinner spanMeeting;

    @OnClick(R2.id.tv_bind)
    void onBind() {
        //todo 绑定设备

        if (StringUtil.isNotEmpty(mSelectProjectId) && StringUtil.isNotEmpty(mSelectMeetingId)) {
            bindMachine();
        } else {
            showLongToast("请选择项目和会议室");
        }

    }

    @OnClick(R2.id.iv_setting)
    void onSetting() {
        showServiceDialog(getContext());
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_machine_set;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        tvMac.setText(OpenUDID.getOpenUDID());
        initProjectData();
    }

    private void initProjectData() {
        AtmosLoader.showLoading(getContext());
        HttpHelper.RestClientGet(HttpUrl.GET_PROJECT_LIST,
                new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        AtmosLoader.stopLoading();
                        Type type = new TypeToken<ProjectListEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        ProjectListEntity mData = gson.fromJson(response, type);
                        if (mData.getStatus().equals(FusionCode.SUCCESS)) {
                            mProjects = mData.getData().getList();
                            projectList.clear();
                            for (ProjectListEntity.DataBean.ListBean data : mData.getData().getList()) {
                                projectList.add(data.getProjectName());
                            }
                            projectList.add("请选择项目");
                            initProjectSpanInfo();
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        AtmosLoader.stopLoading();
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        AtmosLoader.stopLoading();
                    }
                });
    }

    private void initMeetingData(String projectId) {
        AtmosLoader.showLoading(getContext());
        try {
            HttpHelper.RestClientGet(HttpUrl.GET_MEETING_LIST + "?projectId=" + AESUtil.encrypt(projectId),
                    new ISuccess() {
                        @Override
                        public void onSuccess(String response) {
                            AtmosLoader.stopLoading();
                            Type type = new TypeToken<MeetingListEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            MeetingListEntity mData = gson.fromJson(response, type);
                            if (mData.getStatus().equals(FusionCode.SUCCESS)) {
                                mMeetings = mData.getData().getList();
                                meetingList.clear();
                                for (MeetingListEntity.DataBean.ListBean data : mData.getData().getList()) {
                                    meetingList.add(data.getSpaceName());
                                }
                                if (mMeetings == null || mMeetings.size() <= 0) {
                                    meetingList.add("暂无可选会议室");
                                }
                                meetingList.add("请选择会议室");
                                initMeetingSpanInfo();

                            }
                        }
                    }, new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            AtmosLoader.stopLoading();
                        }
                    }, new IFailure() {
                        @Override
                        public void onFailure() {
                            AtmosLoader.stopLoading();
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            AtmosLoader.stopLoading();
        }

    }


    private void bindMachine() {
        AtmosLoader.showLoading(getContext());

        JSONObject params = new JSONObject();
        params.put("deviceId", OpenUDID.getOpenUDID());
        params.put("projectId", mSelectProjectId);
        params.put("spaceId", mSelectMeetingId);

        HttpHelper.RestClientPostRaw(params, HttpUrl.BIND_MACHINE,
                new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        AtmosLoader.stopLoading();
                        Type type = new TypeToken<BindEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        BindEntity mData = gson.fromJson(response, type);
                        if (mData.getStatus().equals(FusionCode.SUCCESS)) {
                            AtmosPreference.addCustomBooleanPre(FusionPre.IS_BIND, true);
                            AtmosPreference.addCustomStringPre(FusionPre.MEETING_ROOM, mSelectMeetingName);
                            EventBus.getDefault().post(new HomeRefreshEvent(new Bundle()));
                            Intent serviceIntent = new Intent(getContext(), HeartBeatService.class);
                            getProxyActivity().startService(serviceIntent);
                        } else {
                            showLongToast(mData.getMsg());
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        AtmosLoader.stopLoading();
                        showLongToast(msg);
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        AtmosLoader.stopLoading();
                        showLongToast("网络异常");
                    }
                });
    }

    public void showServiceDialog(final Context mContext) {
        final Dialog serviceDialog = new Dialog(mContext, R.style.dialog);
        serviceDialog.setCancelable(false);
        Window window = serviceDialog.getWindow();
        window.setContentView(R.layout.dialog_input_service_address);
        int width = (int) (DimenUtil.getScreenWidth() * 0.6);
        int height = (int) (DimenUtil.getScreenHeight() * 0.6);
        window.setLayout(width, height);

        final AppCompatEditText etServiceAddress = window.findViewById(R.id.et_service_address);
        AppCompatTextView tvCancel = window.findViewById(R.id.tv_cancel);
        AppCompatTextView tvSure = window.findViewById(R.id.tv_sure);

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                serviceDialog.dismiss();
            }
        });

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    if (StringUtil.isNotEmpty(etServiceAddress.getText().toString())) {

                        AtmosPreference.addCustomStringPre(FusionPre.SERVICE_ADDRESS, etServiceAddress.getText().toString());
                    } else {
                        DialogUtil.showCardErrorDialog(IndexMachineSetDelegate.this, mContext, getString(R.string.service_address_can_not_null), "确定");
                    }
                }
            }
        });
        etServiceAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etServiceAddress.requestFocus();
                etServiceAddress.setCursorVisible(true);
            }
        });
        serviceDialog.show();
    }

    private void initProjectSpanInfo() {

        //适配器
        IndexSpanAdapter arrAdapter = new IndexSpanAdapter<String>(getContext(), R.layout.simple_spinner_item, projectList);
        //设置样式
        arrAdapter.setDropDownViewResource(R.layout.dropdown_stytle);
        //加载适配器
        spanProject.setAdapter(arrAdapter);
        spanProject.setSelection(projectList.size() - 1, true);
        spanProject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                initMeetingData(String.valueOf(mProjects.get(position).getId()));
                mSelectProjectId = String.valueOf(mProjects.get(position).getId());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void initMeetingSpanInfo() {

        //适配器
        IndexSpanAdapter arrAdapter = new IndexSpanAdapter<String>(getContext(), R.layout.simple_spinner_item, meetingList);
        //设置样式
        arrAdapter.setDropDownViewResource(R.layout.dropdown_stytle);
        //加载适配器
        spanMeeting.setAdapter(arrAdapter);
        spanMeeting.setSelection(meetingList.size() - 1, true);
        spanMeeting.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                try {
                    mSelectMeetingId = String.valueOf(mMeetings.get(position).getId());
                    mSelectMeetingName = mMeetings.get(position).getSpaceName();
                } catch (Exception e) {

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }
}
